<template>
  <section class="todoapp">
    <!-- 头部  -->
    <HradList 
    @keyConter="keyConter"
    ></HradList>

    <!-- 主体 -->
    <BodyList 
    :list="contentList" 
    @changeCss="changeCss" 
    @del="del"
    @allBtn="allBtn"
    ></BodyList>

    <!-- 底部 -->
    <FoodList
    :sum="sum"
    @delBtn="delBtn"
    :showHide="showHide"
    :type="type"
    @changeType="changeType"
    ></FoodList>
  </section>
</template>

<script>
import HradList from './components/HradList.vue'
import BodyList from './components/BodyList.vue'
import FoodList from './components/FoodList.vue'

export default {
  components: {
    HradList,
    BodyList,
    FoodList,
  },

  data() {
    return {
      list: 
      JSON.parse(localStorage.getItem('list')) ||
      [
        {
          id: 1,
          flag: true,
          value: '读万卷书',
        },
        {
          id: 2,
          flag: false,
          value: '行万里路',
        },
      ],
      type:'all'
    }
  },

  methods: {
    // 渲染默认数据事件
    keyConter(value) {
      this.list = [
        ...this.list,
        {
          id: +new Date(),
          flag: false,
          value,
        },
      ]
    },

    // 修改css样式事件
    changeCss(id, flag) {
      this.list.filter((item) => {
        if (item.id === id) return (item.flag = flag)
      })
    },

    // 删除选中事件
    del(id) {
      this.list = this.list.filter((item) => {
        return item.id !== id
      })
    },

    // 删除全部完成事件
    delBtn(){
      this.list = this.list.filter(item=>{
          return !item.flag
      })
    },

    // 改变边框事件
    changeType(type){
      this.type = type
    },

    // 全选事件
    allBtn(flag){
      this.list.forEach(item=>{
          item.flag = flag
      })
    }
  },

  computed:{
    // 剩余未完成的数量
    sum(){
      return this.list.filter(item=>{
        return !item.flag
      }).length
    },

    // 隐藏清除完成键
    showHide(){
      return this.list.some(item=>{
        return item.flag
      })
    },

    // 显示相应的内容
    contentList(){
      if(this.type === 'all'){return this.list}
      else if(this.type === 'active'){return this.list.filter(item=> !item.flag)}
      else if(this.type === 'completed'){return this.list.filter(item=> item.flag)}
      else{return this.list}
    }
  },

  // 深度监听 
  watch:{
    deep:true,
    immediate:true,
    list:{
      handler(newValue){
        // 保存本地
        localStorage.setItem('list',JSON.stringify(newValue))
      }
    }
  }    
}
</script>

<style></style>
